﻿using QLicense;
using System;
using System.ComponentModel;

namespace MultiDAQ_Analysis.License
{
    /// <summary>
    /// 自定义时间许可证类
    /// 继承自QLicense的LicenseEntity基类
    /// </summary>
    [Serializable]
    public class MyTimeLicense : LicenseEntity
    {
        /// <summary>
        /// 应用程序名称
        /// </summary>
        public string AppName { get; set; }

        /// <summary>
        /// 许可证发放日期
        /// </summary>
        public DateTime? IssueDate { get; set; }

        /// <summary>
        /// 许可证到期日期
        /// </summary>
        public DateTime? ExpireDate { get; set; }

        /// <summary>
        /// 设备唯一标识
        /// </summary>
        public string UID { get; set; }

        /// <summary>
        /// 默认构造函数（XML序列化需要）
        /// </summary>
        public MyTimeLicense()
        {
            Type = LicenseTypes.Single;
            IssueDate = DateTime.Now;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="appName">应用程序名称</param>
        /// <param name="expireDate">到期日期</param>
        /// <param name="deviceUID">设备UID</param>
        public MyTimeLicense(string appName, DateTime expireDate, string deviceUID)
        {
            AppName = appName;
            ExpireDate = expireDate;
            UID = deviceUID;
            Type = LicenseTypes.Single;
            IssueDate = DateTime.Now;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="appName">应用程序名称</param>
        /// <param name="expireDate">到期日期</param>
        /// <param name="deviceUID">设备UID</param>
        /// <param name="licenseType">许可证类型</param>
        public MyTimeLicense(string appName, DateTime expireDate, string deviceUID, LicenseTypes licenseType)
        {
            AppName = appName;
            ExpireDate = expireDate;
            UID = deviceUID;
            Type = licenseType;
            IssueDate = DateTime.Now;
        }

        /// <summary>
        /// 执行额外的许可证验证
        /// 这个方法会在QLicense框架验证签名后被调用
        /// </summary>
        /// <param name="validationMsg">验证消息</param>
        /// <returns>验证结果</returns>
        public override LicenseStatus DoExtraValidation(out string validationMsg)
        {
            validationMsg = string.Empty;

            try
            {
                // 1. 检查应用程序名称
                if (string.IsNullOrEmpty(AppName))
                {
                    validationMsg = "许可证中应用程序名称为空";
                    return LicenseStatus.INVALID;
                }

                // 2. 检查设备UID（如果许可证绑定了设备）
                if (!string.IsNullOrEmpty(UID))
                {
                    string currentUID = LicenseHandler.GenerateUID(AppName);
                    if (UID != currentUID)
                    {
                        validationMsg = "许可证与当前设备不匹配";
                        return LicenseStatus.INVALID;
                    }
                }

                // 3. 检查许可证是否过期
                if (ExpireDate.HasValue)
                {
                    if (DateTime.Now > ExpireDate.Value)
                    {
                        validationMsg = $"许可证已于 {ExpireDate.Value:yyyy-MM-dd} 过期";
                        return LicenseStatus.INVALID; // QLicense没有EXPIRED状态，过期时返回INVALID
                    }

                    // 检查是否即将过期（7天内）
                    TimeSpan timeRemaining = ExpireDate.Value - DateTime.Now;
                    if (timeRemaining.TotalDays <= 7 && timeRemaining.TotalDays > 0)
                    {
                        validationMsg = $"许可证将于 {ExpireDate.Value:yyyy-MM-dd} 过期（剩余 {Math.Ceiling(timeRemaining.TotalDays)} 天）";
                        // 仍然返回VALID，但提供警告信息
                    }
                }

                // 4. 检查发放日期是否合理
                if (IssueDate.HasValue && IssueDate.Value > DateTime.Now)
                {
                    validationMsg = "许可证发放日期无效";
                    return LicenseStatus.INVALID;
                }

                // 5. 验证许可证类型
                if (!Enum.IsDefined(typeof(LicenseTypes), Type))
                {
                    validationMsg = "无效的许可证类型";
                    return LicenseStatus.INVALID;
                }

                // 所有验证通过
                if (string.IsNullOrEmpty(validationMsg))
                {
                    if (ExpireDate.HasValue)
                    {
                        TimeSpan remaining = ExpireDate.Value - DateTime.Now;
                        validationMsg = $"许可证有效，剩余 {Math.Ceiling(remaining.TotalDays)} 天";
                    }
                    else
                    {
                        validationMsg = "许可证有效（永久）";
                    }
                }

                return LicenseStatus.VALID;
            }
            catch (Exception ex)
            {
                validationMsg = $"许可证验证过程中发生错误: {ex.Message}";
                return LicenseStatus.INVALID;
            }
        }

        /// <summary>
        /// 获取许可证的友好显示名称
        /// </summary>
        /// <returns>显示名称</returns>
        public string GetDisplayName()
        {
            var name = $"{AppName} - {GetLicenseTypeDisplayName()}";
            if (ExpireDate.HasValue)
            {
                name += $" (到期: {ExpireDate.Value:yyyy-MM-dd})";
            }
            else
            {
                name += " (永久)";
            }
            return name;
        }

        /// <summary>
        /// 获取许可证类型的显示名称
        /// </summary>
        /// <returns>类型显示名称</returns>
        public string GetLicenseTypeDisplayName()
        {
            switch (Type)
            {
                case LicenseTypes.Single:
                    return "单用户许可证";
                case LicenseTypes.Volume:
                    return "批量许可证";
                default:
                    return Type.ToString();
            }
        }

        /// <summary>
        /// 检查许可证是否有效（不包含过期检查）
        /// </summary>
        /// <returns>是否有效</returns>
        public bool IsValid()
        {
            return !string.IsNullOrEmpty(AppName) &&
                   Enum.IsDefined(typeof(LicenseTypes), Type);
        }

        /// <summary>
        /// 检查许可证是否已过期
        /// </summary>
        /// <returns>是否过期</returns>
        public bool IsExpired()
        {
            return ExpireDate.HasValue && DateTime.Now > ExpireDate.Value;
        }

        /// <summary>
        /// 获取剩余天数
        /// </summary>
        /// <returns>剩余天数，永久许可证返回-1</returns>
        public int GetRemainingDays()
        {
            if (!ExpireDate.HasValue)
                return -1; // 永久许可证

            TimeSpan remaining = ExpireDate.Value - DateTime.Now;
            return (int)Math.Ceiling(remaining.TotalDays);
        }

        /// <summary>
        /// 检查许可证是否即将过期
        /// </summary>
        /// <param name="warningDays">提前警告天数</param>
        /// <returns>是否即将过期</returns>
        public bool IsExpiringSoon(int warningDays = 30)
        {
            if (!ExpireDate.HasValue)
                return false; // 永久许可证不会过期

            TimeSpan remaining = ExpireDate.Value - DateTime.Now;
            return remaining.TotalDays <= warningDays && remaining.TotalDays > 0;
        }

        /// <summary>
        /// 重写ToString方法，提供详细信息
        /// </summary>
        /// <returns>许可证信息字符串</returns>
        public override string ToString()
        {
            var info = $"许可证信息:\n";
            info += $"  应用程序: {AppName}\n";
            info += $"  类型: {GetLicenseTypeDisplayName()}\n";
            info += $"  发放日期: {(IssueDate?.ToString("yyyy-MM-dd") ?? "未知")}\n";
            info += $"  到期日期: {(ExpireDate?.ToString("yyyy-MM-dd") ?? "永久")}\n";
            info += $"  设备绑定: {(!string.IsNullOrEmpty(UID) ? "是" : "否")}\n";
            info += $"  当前状态: {(IsExpired() ? "已过期" : "有效")}";
            return info;
        }
    }
}